var express = require('express');
var iPay88Signature = require('../public/js/sha1.js');
var Token = require('../public/easemob/token');
var User = require('../public/easemob/user');
var ChatHistory = require('../public/easemob/chatHistory');
var Files = require('../public/easemob/files');
var Group = require('../public/easemob/group');
var ChatRoom = require('../public/easemob/chatRoom');
var SendMessage = require('../public/easemob/sendMessage');
var router = express.Router();

token = new Token();
user = new User();
chatHistory = new ChatHistory();
files = new Files();
group = new Group();
chatRoom = new ChatRoom();
sendMessage = new SendMessage();
/* GET home page. */
router.all('/', function (req, res, next) {
    //返回的数据
    //suatus:1 成功 0等待  -1 失败
    
    if (req.query.type == "response") {
        let MerChantKey = req.body.MerChantKey; //商户密钥
        let MerChantCode = req.body.MerchantCode; //用戶編號
        let paymentid = req.body.PaymentId; //用戶支付ID
        let orderid = req.body.RefNo; //訂單號
        let amount = req.body.Amount; //總金額
        let curr = req.body.Currency; //貨幣編號
        let remark = req.body.Remark; //備註
        let transid = req.body.TransId; //ipay88事務ID
        let authcode = req.body.AuthCode; //銀行批准碼
        let estatus = req.body.Status; //支付狀態碼，00表示支付成功
        let errdesc = req.body.ErrDesc; //錯誤描述
        let signature = req.body.Signature; //簽名
        let amount_number = toFloat(amount); //數字化金額
        console.log(paymentConfig.paymentKey);
        console.log(paymentConfig.paymentCode);
        console.log(paymentid);
        console.log(orderid);
        console.log(amount_number*100);
        console.log(curr);
        console.log(estatus);
        console.log(signature);
        console.log(paymentConfig.paymentKey + paymentConfig.paymentCode + paymentid + orderid + amount_number*100 + curr + estatus);
        var ipay88Singy = iPay88Signature.iPay88Signature(paymentConfig.paymentKey + paymentConfig.paymentCode + paymentid + orderid + amount_number*100 + curr + estatus);
        if (ipay88Singy == signature) {
            //签名正确，没有被改动
            //支付成功了，先查查单号，然后去更改订单状态-》插入资金明细-》修改用户余额
            if (paymentid == 5) {
                if (estatus == '1') {
                    //立即支付的成功了
                    
                    sqlQuery('money_recharge', '*', {
                        uid: req.query.uid,
                        token: req.query.token,
                        money_sess: orderid
                    }, function (result) {
                        if (result.length > 0) {
                            //查得到这个数据
            
                            
                            sqlQuery('member_table', '*', {
                                member_id: result[0].money_id
                            }, function (result1) {

                                let where = ' where uid="' + req.query.uid + '" and token="' + req.query.token + '" and money_sess="' + orderid + '"';
                                let task1 = sqlUpdateStr('money_recharge', {
                                    status: 1,
                                    approval_date: getNowTime()
                                }, where);
                                let task2 = sqlInsStr('member_money', {
                                    type: 3,
                                    money_sess: getNowTime() + generateMixed(6),
                                    money_id: result[0].money_id,
                                    money_add: result[0].money_add,
                                    money_reason: result[0].money_reason,
                                    money_left: result1[0].member_money + result[0].money_add,
                                    modify_id: result[0].money_id,
                                    modify_ip: getClientIp(req),
                                    register_date: getNowTime(),
                                    approval_date: getNowTime()
                                })
                                let task3 = sqlUpdateStr('member_table', {
                                    member_money: result1[0].member_money + result[0].money_add
                                }, ' where member_id=' + result[0].money_id);

                                Transaction([task1, task2, task3], function (result2) {
                                    if (result2.length > 0) {
                                        //充值成功了
                                        sendMessage.sendCmd({
                                            type: 'users',
                                            target: [result[0].money_id],
                                            action: 'recharge end',
                                            from: 'PHCHAT',
                                            ext: {
                                                status: 1,
                                                account:result[0].money_add
                                            }
                                        });
                                    } else {
                                        //充值失败
                                        sendMessage.sendCmd({
                                            type: 'users',
                                            target: [result[0].money_id],
                                            action: 'recharge end',
                                            from: 'PHCHAT',
                                            ext: {
                                                status: -1,
                                                account:result[0].money_add
                                            }
                                        });
                                    }
                                });
                            });

                        }
                    })
                } 
                else {
            console.log('s5');
                    
                    console.log(req.query.uid);
                    console.log(req.query.token);
                    console.log(orderid);
           
                    sqlQuery('money_recharge', '*', {
                        uid: req.query.uid,
                        token: req.query.token,
                        money_sess: orderid
                    }, function (result) {
                        console.log(result[0].money_id);
                    sendMessage.sendCmd({
                        type: 'users',
                        target: [result[0].money_id],
                        action: 'recharge end',
                        from: 'PHCHAT',
                        ext: {
                            status: -1,
                            account:result[0].money_add
                        }
                    });
                });
                }
            } 
            else if (paymentid == '18' || paymentid == '19' || paymentid == '20') //现金支付
            {
                if (estatus == '6') {
                    //发送成功，等待支付
                    sqlQuery('money_recharge', '*', {
                        uid: req.query.uid,
                        token: req.query.token,
                        money_sess: orderid
                    }, function (result) {
                    sendMessage.sendCmd({
                        type: 'users',
                        target: [result[0].money_id],
                        action: 'recharge end',
                        from: 'PHCHAT',
                        ext: {
                            status: 0,
                            account:result[0].money_add
                        }
                    });
                });
                } else {
                    //支付失败
                    sqlQuery('money_recharge', '*', {
                        uid: req.query.uid,
                        token: req.query.token,
                        money_sess: orderid
                    }, function (result) {
                    sendMessage.sendCmd({
                        type: 'users',
                        target: [result[0].money_id],
                        action: 'recharge end',
                        from: 'PHCHAT',
                        ext: {
                            status: -1,
                            account:result[0].money_add
                        }
                    });
                });
                }
            
            }


        } 
        else {
            //签名不正确，被改动了
            console.log('s6');
            console.log(req.query.uid);
            console.log(req.query.token);
            console.log(orderid);
            sqlQuery('money_recharge', '*', {
                uid: req.query.uid,
                token: req.query.token,
                money_sess: orderid
            }, function (result) {
               
            sendMessage.sendCmd({
                type: 'users',
                target: [result[0].money_id],
                action: 'recharge end',
                from: 'PHCHAT',
                ext: {
                    status: -1,
                    account:result[0].money_add
                }
            });
        });
        }
        
    } else if (req.query.type == "back") {
        res.end('RECEIVEOK');
        let MerChantKey = req.body.MerChantKey; //商户密钥
        let MerChantCode = req.body.MerchantCode; //用戶編號
        let paymentid = req.body.PaymentId; //用戶支付ID
        let orderid = req.body.RefNo; //訂單號
        let amount = req.body.Amount; //總金額
        let curr = req.body.Currency; //貨幣編號
        let remark = req.body.Remark; //備註
        let transid = req.body.TransId; //ipay88事務ID
        let authcode = req.body.AuthCode; //銀行批准碼
        let estatus = req.body.Status; //支付狀態碼，00表示支付成功
        let errdesc = req.body.ErrDesc; //錯誤描述
        let signature = req.body.Signature; //簽名
        let amount_number = toFloat(amount); //數字化金額

        var ipay88Singy = iPay88Signature.iPay88Signature(paymentConfig.paymentKey + paymentConfig.paymentCode + paymentid + orderid + amount_number*100 + curr + estatus);        
        if (ipay88Singy == signature) {
            if (paymentid == '18' || paymentid == '19' || paymentid == '20')//现金支付
            {
                if (estatus == '1') {
                    //立即支付的成功了
                    sqlQuery('money_recharge', '*', {
                        uid: req.query.uid,
                        token: req.query.token,
                        money_sess: orderid
                    }, function (result) {
                        if (result.length > 0) {
                            //查得到这个数据
                            sqlQuery('money_table', '*', {
                                member_id: result[0].money_id
                            }, function (result1) {

                                let where = ' where uid="' + req.query.uid + '" and token="' + req.query.token + '" and money_sess="' + orderid + '"';
                                let task1 = sqlUpdateStr('money_recharge', {
                                    status: 1,
                                    approval_date: getNowTime()
                                }, where);
                                let task2 = sqlInsStr('member_money', {
                                    type: 3,
                                    money_sess: getNowTime() + generateMixed(6),
                                    money_id: result[0].money_id,
                                    money_add: result[0].money_add,
                                    money_reason: result[0].money_reason,
                                    money_left: result1[0].member_money + result[0].money_add,
                                    modify_id: result[0].money_id,
                                    modify_ip: getClientIp(req),
                                    register_date: getNowTime(),
                                    approval_date: getNowTime()
                                })
                                let task3 = sqlUpdateStr('member_table', {
                                    member_money: result1[0].member_money + result[0].money_add
                                }, ' where member_id=' + result[0].money_id);

                                Transaction([task1, task2, task3], function (result2) {
                                    if (result2.length > 0) {
                                        //充值成功了
                                        sendMessage.sendCmd({
                                            type: 'users',
                                            target: [result[0].money_id],
                                            action: 'recharge end',
                                            from: 'PHCHAT',
                                            ext: {
                                                status: 1,
                                                account:result[0].money_add
                                            }
                                        });
                                    } else {
                                        //充值失败
                                        sendMessage.sendCmd({
                                            type: 'users',
                                            target: [result[0].money_id],
                                            action: 'recharge end',
                                            from: 'PHCHAT',
                                            ext: {
                                                status: -1,
                                                account:result[0].money_add
                                            }
                                        });
                                    }
                                });
                            });

                        }
                    })
                } 
                else {
                    sqlQuery('money_recharge', '*', {
                        uid: req.query.uid,
                        token: req.query.token,
                        money_sess: orderid
                    }, function (result) {
                    sendMessage.sendCmd({
                        type: 'users',
                        target: [result[0].money_id],
                        action: 'recharge end',
                        from: 'PHCHAT',
                        ext: {
                            status: -1,
                            account:result[0].money_add
                        }
                    });
                });
                }
            }
            else{
                sqlQuery('money_recharge', '*', {
                    uid: req.query.uid,
                    token: req.query.token,
                    money_sess: orderid
                }, function (result) {
                sendMessage.sendCmd({
                    type: 'users',
                    target: [result[0].money_id],
                    action: 'recharge end',
                    from: 'PHCHAT',
                    ext: {
                        status: -1,
                        account:result[0].money_add
                    }
                });
            });
            }
        }
        else{
            
            sqlQuery('money_recharge', '*', {
                uid: req.query.uid,
                token: req.query.token,
                money_sess: orderid
            }, function (result) {
            sendMessage.sendCmd({
                type: 'users',
                target: [result[0].money_id],
                action: 'recharge end',
                from: 'PHCHAT',
                ext: {
                    status: -1,
                    account:result[0].money_add
                }
            });
        });
        }

    } 
    else {
        //错误的回调
        sendMessage.sendCmd({
            type: 'users',
            target: [result[0].money_id],
            action: 'recharge end',
            from: 'PHCHAT',
            ext: {
                status: -1,
                account:result[0].money_add
            }
        });
    }
});

module.exports = router;